import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:xcite/core/services/open_launcher.dart';
import 'package:xcite/core/utils/ali.dart';

import '../../core/providers/topic_provider.dart';
import '../../core/providers/user_provider.dart';
import '../../core/utils/popup_helper.dart';
import '../../core/utils/toast_helper.dart';

class CreateTopicScreen extends ConsumerStatefulWidget {
  const CreateTopicScreen({super.key});

  @override
  ConsumerState<CreateTopicScreen> createState() => _CreateTopicScreenState();
}

class _CreateTopicScreenState extends ConsumerState<CreateTopicScreen> {
  final TextEditingController _topicController = TextEditingController();
  bool _isCreating = false;

  @override
  void dispose() {
    _topicController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/resources/common_bg_2.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child:
              [
                _buildTopNavigationBar(),
                SizedBox(height: 40.h),
                _buildMainContent().expanded(),
              ].toColumn(),
        ),
      ),
    );
  }

  Widget _buildTopNavigationBar() {
    return [
      Container(
        width: 30.w,
        height: 30.w,
        decoration: BoxDecoration(color: Colors.black, shape: BoxShape.circle),
        child:
            Icon(
              Icons.arrow_back_ios_new,
            ).iconSize(20.sp).iconColor(Colors.white).center(),
      ).inkWell(onTap: () => GoRouter.of(context).pop()),
      Expanded(
        child: Text(
          'Release',
          textAlign: TextAlign.center,
          style: TextStyle(
            fontSize: 24.sp,
            fontWeight: FontWeight.bold,
            color: Colors.black,
            fontFamily: 'PoetsenOne',
          ),
        ),
      ),
      SizedBox(width: 40.w),
    ].toRow().padding(horizontal: 16.w, vertical: 20.h);
  }

  Widget _buildMainContent() {
    return [
      _buildInputContainer(),
      SizedBox(height: 68.h),
      _buildCreateButton(),
      const Spacer(),
      _buildEulaText(),
      SizedBox(height: 40.h),
    ].toColumn().padding(horizontal: 16.w);
  }

  Widget _buildInputContainer() {
    return AspectRatio(
      aspectRatio: 374 / 374,
      child: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/resources/create_input.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: Stack(
          children: [
            Container(
              padding: EdgeInsets.all(24.w),
              child: TextField(
                controller: _topicController,
                maxLines: null,
                expands: true,
                textAlignVertical: TextAlignVertical.top,
                textInputAction: TextInputAction.done,
                style: TextStyle(
                  fontSize: 16.sp,
                  color: Colors.black,
                  height: 1.5,
                ),
                decoration: InputDecoration(
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.zero,
                ),
                onChanged: (value) {
                  setState(() {});
                },
              ),
            ),
            if (_topicController.text.isEmpty)
              [
                    Icon(
                      AliIcons.iconTopic,
                    ).iconSize(32.sp).iconColor(Color(0xFF2AB061)),
                    SizedBox(height: 8.h),
                    Text(
                      'Enter a Topic',
                      style: TextStyle(
                        fontSize: 16.sp,
                        color: Colors.black,
                        fontFamily: 'PoetsenOne',
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ]
                  .toColumn(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                  )
                  .center(),
          ],
        ),
      ),
    );
  }

  Widget _buildCreateButton() {
    return Container(
      height: 56.h,
      width: double.infinity,
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/resources/create_button.png'),
          fit: BoxFit.fill,
        ),
      ),
    ).inkWell(onTap: _isCreating ? null : _createTopic);
  }

  /// EULA
  Widget _buildEulaText() {
    return Text(
      'EULA',
      style: TextStyle(
        fontSize: 14.sp,
        color: Colors.white,
        decoration: TextDecoration.underline,
        decorationColor: Colors.white,
      ),
    ).center().inkWell(onTap: _showEula);
  }

  Future<void> _createTopic() async {
    final content = _topicController.text.trim();
    if (content.isEmpty) {
      ToastHelper.error('Please enter topic content', context: context);
      return;
    }

    final currentUser = ref.read(currentUserProvider);
    if (currentUser == null) {
      PopupHelper.showLoginDialog(
        context,
        onLoginPressed: () {
          GoRouter.of(context).push('/login');
        },
        onCancelPressed: () {},
      );
      return;
    }

    setState(() {
      _isCreating = true;
    });

    try {
      final topicNotifier = ref.read(outingTopicProvider.notifier);
      final success = await topicNotifier.addTopic(
        userId: currentUser.id,
        description: content,
      );

      if (mounted) {
        setState(() {
          _isCreating = false;
        });

        if (success) {
          ToastHelper.success('Topic created successfully!', context: context);
          GoRouter.of(context).pop();
        } else {
          ToastHelper.error('Failed to create topic', context: context);
        }
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isCreating = false;
        });
        ToastHelper.error('Failed to create topic', context: context);
      }
    }
  }

  void _showEula() {
    Open.openLaunch(
      'https://www.freeprivacypolicy.com/live/2908db45-eaa5-4be2-bf12-428f9bbadb26',
    );
  }
}
